import 'dart:convert';
import 'dart:io';

import 'package:bot_toast/bot_toast.dart';
import 'package:csv/csv.dart';

import 'package:file_selector/file_selector.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'package:path_provider/path_provider.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '数据编码处理',
      builder: BotToastInit(),
      navigatorObservers: [BotToastNavigatorObserver()],
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'csv处理'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String fileName = "暂未选取文件";
  String path = '';
  List<List<String>> csv = [];

  Future<void> _incrementCounter() async {
    const xType = XTypeGroup(label: 'csv文件  ', extensions: ['csv']);
    XFile? file = await openFile(acceptedTypeGroups: [xType]);

    if (!file!.name.endsWith(".csv")) {
      BotToast.showText(text: '请选择csv文件啦😤');
      return;
    }
    setState(() {
      path = file.path;
      fileName = "处理文件:${file?.name}\n文件路径:${file?.path}";
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme
            .of(context)
            .colorScheme
            .inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              '点击右下角按钮选择要处理的csv文件\n',
              style: Theme
                  .of(context)
                  .textTheme
                  .headlineMedium,
            ),
            Text(
              '$fileName\n\n',
            ),
            TextButton(
                onPressed: fileName == "暂未选取文件" ? null : changeExcel,
                child: const Text('开始执行'))
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: '选择文件',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  Future<void> changeExcel() async {
    readCsv();
    changeCsv();
    csv = [];
  }

  changeCsv() {
    String aoi = csv[1][3];
    int sx = 0;
    int cp = 0;
    for (int i = 2; i < csv.length; i++) {
      if(i==14){
        print('5');
      }
      /// 处理属性-tran
      if (csv[i][3] != "") {
        int num = 0;
        csv[i][3] = csv[i][3].trim();
        // 和上面比
        if (csv[i][3][2] == aoi[2] && csv[i][3][1] != aoi[1]) {
          sx++;
          num++;
        }
        // 前后对比
        if (csv[i][3].length > 5) {
          String last = csv[i][3].substring(csv[i][3].length - 3);
          if (csv[i][3][2] == last[2] && csv[i][3][1] != last[1]) {
            sx++;
            num++;
          }
        }

        if (num > 0) {
          csv[i][6] = num.toString();
        }else{
          csv[i][6] = "";
        }
      }

      /// 处理产品-tran
      if (csv[i][3] != "") {
        int num = 0;
        csv[i][3] = csv[i][3].trim();
        // 上下对比
        if (csv[i][3][1] == aoi[1] && csv[i][3][2] != aoi[2]) {
          num++;
          cp++;
        }
        // 前后对比
        if (csv[i][3].length > 5) {
          String last = csv[i][3].substring(csv[i][3].length - 3);
          if (csv[i][3][1] == last[1] && csv[i][3][2] != last[2]) {
            cp++;
            num++;
          }
          csv[i][3] = last;
        }

        if (num > 0) {
          csv[i][7] = num.toString();
        }else{
          csv[i][7] = "";
        }
      }
      if(csv[i][7].length>0)
      print("${i + 1}::::${csv[i][7]}");


      /// 处理con
      aoi = csv[i][3] == "" ? aoi : csv[i][3];
      if (aoi[0] == "C" || aoi[0] == "c") {
        csv[i][5] = "0";
      } else if (aoi[0] == "E" || aoi[0] == "e") {
        csv[i][5] = "1";
      }
    }
    csv[1].add(sx.toString());
    csv[1].add(cp.toString());
    csv[0].add("属性-sacc");
    csv[0].add("产品-sacc");
    print(cp);
  }

  readCsv() {
    File file = File(path);
    List<String> lines;
    try {
      lines = file.readAsLinesSync();
    } catch (e) {
      lines = file.readAsLinesSync(encoding: latin1);
    }
    print(lines.length);
    for (int i = 0; i < lines.length; i++) {
      List<String> line = lines[i].split(",");
      csv.add(line);
    }
    print(csv.length);
  }
}
